<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generator函数</title>
</head>
<body>
    <script>
        function timeout(time){
            return new Promise((resolve, reject)=>{
                try{
                    setTimeout(()=>{
                        resolve(time);
                    }, time);
                }catch(e){
                    reject(e);
                }
            })
        }

        function * createGenerator(){
            let result1 = yield timeout(1000);
            console.log('result1...', result1);
            let result2 = yield timeout(2000);
            console.log('result2...', result2);
            let result3 = yield timeout(3000);
            console.log('result3...', result3);
            let result4 = yield timeout(4000);
            console.log('result4...', result4);
            let result5 = yield timeout(5000);
            console.log('result5...', result5);

            return 6;
        }
        /**
         *  generator函数第一次执行，返回的是迭代器
         *  next方法去执行语句，遇到yield或者return停止，调用下一个next继续执行
         *  返回函数执行状态{value: any(yield后表达式的返回结果), done: boolean(是否执行结束)}
         *  yield表达式的返回结果是下一次调用next传入的值
         */
        // let gen = createGenerator();
        // console.log('gen...', gen);
        // for (let i=0; i<6; i++){
        //     let funcResult = gen.next(i);
        //     console.log(`funcResult${i}...`, funcResult);
        // }

        // generator函数自动执行器
        function run(geneFunc){
            let gen = geneFunc();
            function temp(value){
                let result = gen.next(value);
                if (result.done){
                    return result.value;
                }else{
                    if (typeof result.value.then === 'function' && typeof result.value.catch === 'function'){
                        result.value.then(res=>{
                            temp(res);
                        }, err=>{
                            return err;
                        })
                    }else{
                        temp(result.value);
                    }
                }
            }

            temp();
        }

        run(createGenerator);
    </script>
</body>
</html>